const positionModel = require('../models/position')
const { responseWrite } = require('./common')
const moment = require('moment')

exports.add = (req, res, next) => {
    let body = req.body
    if( !body.companyName || !body.positionName || !body.city || !body.salary ){
        responseWrite(res, {message: "提交信息包含空值"}, 300)
        return;
    }
    positionModel.savePosition({
            ...body,
            publishTime: moment().format('YYYY年MM月DD日 HH:mm')
        }).then(result => {
            if( result ){
                responseWrite(res, {message: "添加成功"})
            }else{
                responseWrite(res, {message: "添加失败, 请重试"}, 300)
            }
        })
}

exports.list = (req, res, next) => {
    positionModel.findPosList().then(result => {
        if( result ){
            responseWrite(res, {posList: result})
        }else{
            responseWrite(res, {message: "获取列表失败"}, 300)
        }
    })
}

exports.remove = (req, res, next) => {
    positionModel.deletePosById(req.body.id).then(result => {
        if( result.deletedCount ){
            responseWrite(res, {message: "删除成功"})
        }else{
            responseWrite(res, {message: "删除失败, 请重试"}, 300)
        }
    })
}

exports.update = (req, res, next) => {
    const objKey = ['id', 'companyName', 'positionName', 'city', 'salary']
    let body = req.body
    console.log(body)
    let _set = {}
    // 用来保存标记: 是否继续执行以下代码(逻辑代码)
    let flag = true
    // 根据key获取请求数据中的内容, 用来筛选修改的数据
    objKey.some(key => {
        if( !body[key] ) {
            flag = false
            responseWrite(res, {message: "请求的数据包括空信息"}, 300)
            return false;
        }else{
            // 保存键值对数据
            _set[key] = body[key]
        }
    })
    if( flag ){
        positionModel.updateById(body.id, _set).then(result => {
            if( result ){
                responseWrite(res, {message: "修改成功"})
            }else{
                responseWrite(res, {message: "修改失败, 请重试"}, 300)
            }
        })
    }
}

exports.findOne = (req, res, next) => {
    let _id = req.query.id
    console.log(_id)
    positionModel.findPosById(_id).then(position => {
        if( position ){
            responseWrite(res, {position})
        }else{
            responseWrite(res, {message: "获取错误, 请重试"}, 300)
        }
    })
}
